package com.chat.controller;

import com.chat.entry.vo.auto.RefreshTokenVO;
import com.chat.result.Result;
import com.chat.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = "刷新accessToken")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @ApiOperation(value = "刷新access_token", notes = "刷新成功")
    @PostMapping("/refresh")
    public Result refreshAccessToken(
            @ApiParam(value = "access_token", required = true) @RequestHeader("Authorization") String refreshToken
    ) {
        try {
            Claims claims = JwtUtil.parseToken(refreshToken);
            //判断是不是refresh_token
            if (!claims.getSubject().equals("REFRESH_TOKEN")) {
                return Result.error("非法的 refresh_token");
            }

            // 判断refreshToken是否过期，过期了就重新登录获取
            boolean isExpired = JwtUtil.isExpired(refreshToken);
            if (isExpired) {
                return Result.error("refresh_token 已过期");
            }

            // 从 claims 获取用户信息
            Integer userId = (Integer) claims.get("userId");
            String username = (String) claims.get("username");

            // 生成新的 accessToken
            String newAccessToken = JwtUtil.generateAccessToken(userId, username);

            return Result.success("刷新成功", new RefreshTokenVO(newAccessToken));
        } catch (Exception e) {
            log.error("刷新 accessToken 失败", e);
            return Result.error("refreshToken 无效，请重新登录");
        }
    }

}
